<template>
  <div class="bacc">
    <div class="cont">
      <div class="login_left">
        <div class="login-logo">
          <Transition name="fade-zoom">
            <img
              v-if="isVisible"
              src="../../assets/启动.svg"
              alt="启动图标"
              class="animated-img"
            />
          </Transition>
        </div>
      </div>
      <div class="login-body">
        <div class="logintop">
          <div class="login-title">HT</div>
        </div>
        <div class="login-form">
          <el-form
            ref="loginFormref"
            :model="HomeFormdata"
            :rules="loginRules"
            @submit.prevent="doSubmit"
          >
            <!-- <div class="login-title">
              <h2>TT云盘</h2>
            </div> -->
            <!-- 邮箱 -->
            <el-form-item prop="email" label="">
              <el-input
                placeholder="请输入邮箱"
                clearable
                v-model.trim="HomeFormdata.email"
                maxlength="150"
              >
                <template #prefix>
                  <el-icon>
                    <User />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <!-- 登陆密码 -->
            <el-form-item prop="password" label="" v-if="onType == 1">
              <el-input
                placeholder="请输入密码"
                clearable
                v-model.trim="HomeFormdata.password"
                show-password
              >
                <template #prefix>
                  <el-icon>
                    <Lock />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <!-- 注册 -->
            <div v-if="onType == 0 || onType == 2">
              <el-form-item prop="emailCode" label="">
                <div class="send-emailCode">
                  <el-input
                    placeholder="请输入邮箱验证码"
                    clearable
                    v-model.trim="HomeFormdata.emailCode"
                    maxlength="50"
                  >
                    <template #prefix>
                      <el-icon>
                        <User />
                      </el-icon>
                    </template>
                  </el-input>
                  <el-button
                    type="primary"
                    @click="getemailCode"
                    style="width: 30%; margin-left: 30px"
                    >获取验证码</el-button
                  >
                </div>

                <el-popover
                  ref="popover"
                  placement="left"
                  :width="200"
                  trigger="hover"
                >
                  <div class="popover-content">
                    <p>1.在垃圾邮箱中查找邮箱验证码</p>
                  </div>
                  <template #reference>
                    <span class="a-hint">未收到验证码?</span>
                  </template>
                </el-popover>
              </el-form-item>
            </div>
            <!-- 昵称 -->
            <el-form-item prop="nickName" label="" v-if="onType == 0">
              <el-input
                placeholder="请输入昵称"
                clearable
                v-model.trim="HomeFormdata.nickName"
                maxlength="150"
              >
                <template #prefix>
                  <el-icon>
                    <User />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <!-- 注册密码,找回密码 -->
            <el-form-item
              prop="registerpassword"
              label=""
              v-if="onType == 0 || onType == 2"
            >
              <el-input
                placeholder="请输入密码"
                clearable
                v-model.trim="HomeFormdata.registerpassword"
                show-password
              >
                <template #prefix>
                  <el-icon>
                    <Lock />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item
              prop="reRegisterpassword"
              label=""
              v-if="onType == 0 || onType == 2"
            >
              <el-input
                placeholder="请再次输入密码"
                clearable
                v-model.trim="HomeFormdata.reRegisterpassword"
                show-password
              >
                <template #prefix>
                  <el-icon>
                    <Lock />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <!-- 验证码 -->
            <el-form-item prop="captcha" label="">
              <div class="captcha-container">
                <el-input
                  placeholder="请输入验证码"
                  v-model.trim="HomeFormdata.captcha"
                  maxlength="150"
                  @keyup.enter="doSubmit"
                  input-style="max-width: 174px;"
                >
                </el-input>
                <img
                  class="captcha-img"
                  :src="captchaUrl"
                  alt=""
                  @click="getCaptcha(0)"
                />
              </div>
            </el-form-item>
            <!-- 登录记住我 -->
            <el-form-item prop="rememberMe" label="" v-if="onType == 1">
              <div class="remember">
                <el-checkbox v-model="HomeFormdata.rememberMe"
                  >记住我</el-checkbox
                >
              </div>
              <div class="no-account">
                <a href="javascript:void(0)" @click="showtable(2)">忘记密码</a>
                <a href="javascript:void(0)" @click="showtable(0)">没有账号?</a>
              </div>
            </el-form-item>
            <el-form-item prop="rememberMe" label="" v-if="onType == 2">
              <div class="remember">
                <el-checkbox v-model="HomeFormdata.rememberMe"
                  >记住我</el-checkbox
                >
              </div>
              <div class="no-account">
                <a href="javascript:void(0)" @click="showtable(1)">去登录</a>
                <a href="javascript:void(0)" @click="showtable(0)">没有账号?</a>
              </div>
            </el-form-item>
            <el-form-item prop="rememberMe" label="" v-if="onType == 0">
              <div class="remember">
                <el-checkbox v-model="HomeFormdata.rememberMe"
                  >记住我</el-checkbox
                >
              </div>
              <div class="no-account">
                <a href="javascript:void(0)" @click="showtable(1)">去登录</a>
                <a href="javascript:void(0)" @click="showtable(2)">忘记密码?</a>
              </div>
            </el-form-item>

            <!-- 登录 -->
            <el-form-item>
              <el-button type="primary" @click="doSubmit" v-if="onType == 1"
                >登录</el-button
              >
              <el-button type="primary" @click="doSubmit" v-if="onType == 0"
                >注册</el-button
              >
              <el-button type="primary" @click="doSubmit" v-if="onType == 2"
                >重置密码</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <MyDialog
          v-model:visible="DialogVisibleconfigSendMailCode.visible"
          :title="DialogVisibleconfigSendMailCode.title"
          :buttons="DialogVisibleconfigSendMailCode.buttons"
        >
          <!-- 弹窗内容 -->
          <el-form
            :model="DialogVisibleconfigSendMailCode"
            :rules="loginRules"
            ref="SendMailCoderef"
            @submit.prevent
            label-width="110px"
          >
            <el-form-item label="Your email:">
              {{ SendMailCode.email }}
            </el-form-item>
            <el-form-item prop="SendEMailCode" label="*验证码">
              <div class="captcha-container">
                <el-input
                  placeholder="请输入验证码"
                  clearable
                  v-model.trim="SendMailCode.checkCode"
                >
                </el-input>
                <img
                  class="captcha-img"
                  :src="DialogcaptchaUrl"
                  alt=""
                  @click="getCaptcha(1)"
                />
              </div>
            </el-form-item>
          </el-form>

          <!-- 自定义底部按钮 -->
          <!-- <template #footer>
                                <el-button @click="handleCustomButton1">自定义按钮 1</el-button>
                                <el-button type="primary" @click="handleCustomButton2">自定义按钮 2</el-button>
                        </template> -->
        </MyDialog>
      </div>
    </div>
  </div>
</template>

<script setup>
import md5 from "js-md5";
import { ref, reactive, getCurrentInstance, nextTick, onMounted } from "vue";
const { proxy } = getCurrentInstance();
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();
const isVisible = ref(false);
onMounted(() => {
  isVisible.value = true; // 挂载时显示并播放动画
  showtable(1);
});

console.log(proxy.request);
// 操作类型:0注册1登录2忘记密码
const onType = ref(1);
const showtable = (type) => {
  onType.value = type;
  resetForm();
};

const api = {
  Captcha: "/api/checkCode",
  sendEMailCode: "/sendEmailCode",
  login: "/login",
  register: "/register",
  resetPwd: "/resetPwd",
  qqlogin: "/qqlogin",
};
const captchaUrl = ref(api.Captcha);
const DialogcaptchaUrl = ref(api.Captcha);

const getCaptcha = (type) => {
  const timestamp = new Date().getTime();

  if (type === 1) {
    DialogcaptchaUrl.value =
      api.Captcha + "?type=" + type + "&time=" + timestamp;
  } else if (type === 0) {
    captchaUrl.value = api.Captcha + "?type=" + type + "&time=" + timestamp;
  }
};
const loginFormref = ref();
const HomeFormdata = ref({
  email: "",
  password: "",
  captcha: "",
  rememberMe: false,
  nickName: "",
  registerpassword: "",
  emailCode: "",
  reRegisterpassword: "",
});
const validatePasswordMatch = (rule, value, callback) => {
  if (value !== HomeFormdata.value.registerpassword) {
    callback(new Error(rule.message));
  } else {
    callback();
  }
};
const loginRules = reactive({
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 8, max: 200, message: "密码长度为8-16位", trigger: "blur" },
  ],
  captcha: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 5, max: 5, message: "验证码长度为5位", trigger: "blur" },
  ],
  nickName: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    { min: 2, max: 15, message: "昵称长度为2-150位", trigger: "blur" },
  ],
  reRegisterpassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    { min: 8, max: 18, message: "密码不相同", trigger: "blur" },
    { validator: validatePasswordMatch, trigger: "blur" }, // 添加自定义验证
  ],
  registerpassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 8, max: 18, message: "密码长度为8-16位", trigger: "blur" },
  ],
  emailCode: [
    { required: true, message: "请输入邮箱验证码", trigger: "blur" },
    { min: 5, max: 5, message: "验证码错误", trigger: "blur" },
  ],
});

const SendMailCoderef = ref();
const SendMailCode = ref({});
// 控制弹窗显示状态
const DialogVisibleconfigSendMailCode = reactive({
  visible: false,
  title: "发送邮件验证码",
  buttons: [
    {
      text: "取消",
      type: "primary",
      click: () => {
        DialogVisibleconfigSendMailCode.visible = false;
      },
    },
    {
      text: "确定",
      type: "primary",
      click: () => {
        sendMailCode();
        // DialogVisibleconfigSendMailCode.visible = false;
      },
    },
  ],
});
const sendMailCode = async () => {
  SendMailCoderef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
  });

  const params = Object.assign({}, SendMailCode.value);
  params.type = onType.value == 0 ? 0 : 1;
  let result = await proxy.request({
    url: api.sendEMailCode,
    errorCallback: () => {
      getCaptcha(1);
    },
    params,
  });
  if (!result) {
    return;
  }
  proxy.Mymessage.success("验证码发送成功,请查看邮箱");
  DialogVisibleconfigSendMailCode.visible = false;
};

const getemailCode = () => {
  loginFormref.value.validateField("email", (valid) => {
    if (valid) {
      // 验证通过，执行登录逻辑
      console.log("验证通过，执行登录逻辑");
      DialogVisibleconfigSendMailCode.visible = true;
      nextTick(() => {
        getCaptcha(2);
        SendMailCoderef.value.resetFields();
        SendMailCode.value = {
          email: HomeFormdata.value.email,
        };
      });
    } else {
      // 验证失败，提示错误信息
      console.log("验证失败，请检查输入信息");
    }
  });
};
//重置表单
const resetForm = () => {
  loginFormref.value.resetFields();
  HomeFormdata.value = {};
  getCaptcha(0);
  if (onType.value === 1) {
    const cookieLoginInfo = proxy.VueCookies.get("loginInfo");
    if (cookieLoginInfo) {
      HomeFormdata.value = cookieLoginInfo;
    }
  }
};

const doSubmit = () => {
  loginFormref.value.validate(async (valid, fields) => {
    if (!valid) {
      // for (const field in fields) {
      //         proxy.Mymessage.error(`${fields[field][0].message}`);
      // }
      const firstField = Object.keys(fields)[0];
      const firstErrorMessage = fields[firstField][0].message;
      console.log(`字段 ${firstField} 验证失败: ${firstErrorMessage}`);
      proxy.Mymessage.error(
        `字段 ${firstField} 验证失败: ${firstErrorMessage}`
      );
      return;
    }
    let params = {};
    Object.assign(params, HomeFormdata.value);
    // 注册找回密码
    if (onType.value == 0 || onType.value == 2) {
      params.password = params.registerpassword;
      params.checkCode = params.captcha;
      delete params.captcha;
      delete params.registerpassword;
      delete params.reRegisterpassword;
    }
    if (onType.value == 1) {
      let cookieLoginInfo = proxy.VueCookies.get("loginInfo");
      let cookiePassword =
        cookieLoginInfo == null ? null : cookieLoginInfo.password;
      if (params.password !== cookiePassword) {
        params.password = md5(params.password);
      }
      params.checkCode = params.captcha;
    }
    let url = null;

    if (onType.value == 0) {
      url = api.register;
    } else if (onType.value == 1) {
      url = api.login;
    } else if (onType.value == 2) {
      url = api.resetPwd;
    }
    let result = await proxy.request({
      url,
      errorCallback: () => {
        getCaptcha(0);
      },
      params,
    });
    if (!result) {
      return;
    }
    if (onType.value == 0) {
      proxy.Mymessage.success("注册成功,请登录");
      //跳转到登录
      showtable(1);
    } else if (onType.value == 1) {
      if (params.rememberMe) {
        const loginInfo = {
          email: params.email,
          password: params.password,
          rememberMe: params.rememberMe,
        };
        proxy.VueCookies.set("loginInfo", loginInfo, 7 * 24 * 60 * 60 * 1000);
      } else {
        proxy.VueCookies.remove("loginInfo");
      }
      //存储cookie
      proxy.VueCookies.set("userInfo", result.data, 0);
      let redirectUrl = route.query.redirectUrl || "/";
      router.push(redirectUrl);
      proxy.Mymessage.success("登录成功");
    } else if (onType.value == 2) {
      proxy.Mymessage.success("密码重置成功");
      //跳转到登录
      showtable(1);
    }
  });
};
</script>

<style lang="scss" scoped>
.fade-zoom-enter-active {
  animation: fadeInZoom 0.6s ease-in forwards;
}

@keyframes fadeInZoom {
  0% {
    opacity: 0.3;
    transform: translate(-50%, -10%);
  }
  50% {
    opacity: 0.7;
    // transform: translate(0%, 0);
  }
  100% {
    opacity: 1;
    transform: translate(0%, 0);
  }
}
@keyframes customAnimation {
  0% {
    opacity: 0;
    transform: translate(40%, -50%) scale(0.5);
  }
  100% {
    opacity: 1;
    transform: translate(0%, 0%) scale(1);
  }
}
.login-body {
  display: flex;
  position: relative;
  // justify-content: space-around;
  flex-direction: column;
  align-items: center;
  width: 35%;
  overflow: hidden;
  height: 100%;
  background-color: #ffffff;
  border-radius: 10px;
  // box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
  z-index: 3;
  // clip-path: polygon(
  //   0 0%,
  //   100% 0%,
  //   calc(25 / 35 * 100%) 100%,
  //   0% 100%
  // ); // 梯形裁剪
  .logintop {
    background-color: #ffffff;
    height: 2.7rem;
    width: 2.7rem;
    display: grid;
    position: absolute;
    right: 2%;
    top: 3%;
    transform: translateY(-50%); // 垂直居中
    margin-top: 0.4rem;
    place-items: center;
    border-radius: 20%;
    .login-title {
      color: #4fb4f7;
    }
  }
  &::after {
    content: "";
    position: absolute;
    top: 0;
    right: 0;
    width: 30%;
    height: 15%;
    z-index: -2;
    border-radius: 50%;
    background-color: #0984ff;
    // border-radius: 30%;
    transform: translate(40%, -50%) scale(1.4) rotate(65deg);
  }
  &::before {
    content: "";
    position: absolute;
    top: 10%;
    right: 20%;
    width: 1rem;
    height: 1rem;
    z-index: -2;
    border-radius: 50%;
    background-color: #0984ff;
    // border-radius: 30%;
    transform: translate(40%, -50%) scale(1.4) rotate(65deg);
    animation: customAnimation 1.5s ease-in-out forwards;
  }
}

.captcha-container {
  display: flex;
  justify-content: flex-start;
  flex-wrap: nowrap;
  align-items: flex-start;
}

.login-form {
  background-color: rgba(255, 255, 255, 0.9);
  padding: 0 2rem 0 0;
  position: absolute;
  top: 15%;
  display: flex;
  align-items: center;
  justify-content: center;
  // border-radius: 15px;
  // box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
  width: 80%;
  height: 70%;
  // background-color: #0984ff;

  .remember {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .send-emailCode {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }

  .a-hint {
    color: #007bff;
    text-align: left;
  }

  .no-account {
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 14px;

    a {
      color: #007bff; // 默认颜色
      text-decoration: none; // 去掉下划线

      &:hover {
        color: #f1e3aa; // 悬停时颜色
      }

      &:active {
        color: #000000; // 点击时颜色
      }
    }
  }
}

.captcha-img {
  width: 40%;
  height: calc(var(--el-input-height, 32px) - 2px);
  cursor: pointer;
  margin-left: calc(var(--el-input-height, 32px) - 9px);
}

.el-button {
  width: 100%;
  padding: 10px;
}
.bacc {
  position: relative;
  overflow: hidden; // 关键：防止伪元素溢出
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  .cont {
    width: 85%;
    height: 85%;
    display: flex;
    border-radius: 1rem;
    justify-content: center;
    align-items: center;
    overflow: hidden;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);

    background-color: #ffffff;
  }
  .login_left {
    background-image: radial-gradient(circle, #a0c4ff, #0984ff);
    // clip-path: polygon(0 0%, 100% 0%, 100% 100%, 0% 100%); // 梯形裁剪
    // box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
    flex: 1.3;
    height: 100%;
    overflow: hidden;
    position: relative;
    .login-logo {
      height: 100%;
      img {
        width: 100%;
        // height: 70%;
        margin-top: 10%;
        position: absolute;
        z-index: 2;
        background: no-repeat center;
      }
    }
    &::after {
      content: "";
      position: absolute;
      bottom: 0;
      right: 0;
      z-index: -2s;
      width: calc(10 / 35 * 100%); // 略大于父元素，防止倾斜后留白
      height: 100%;
      background-color: #ffffff;
      transform: skewY(-70deg);
      transform-origin: bottom right;
    }
  }
}

.bacc::after,
.bacc::before {
  content: "";
  position: absolute;
  z-index: -3;
  width: 16vw; // 使用视口单位适配不同屏幕
  height: 10vw;
  border-radius: 50%;
  background-color: #007bff;
  transform: scale(2) rotate(25deg); // 降低 scale 值
}

.bacc::after {
  left: 0;
  bottom: 0;
  border-radius: 30%;
  transform: translate(-50%, 50%) scale(3) rotate(25deg);
}

.bacc::before {
  right: 0;
  top: 0;
  transform: translate(50%, 50%) scale(3) rotate(25deg);
}
</style>